package com.open.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.open.bean.vo.OpenVo;
import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@Slf4j
public class StrAnalysisUtil {

    public static ScriptEngine engine;

    
    public static OpenVo analysis(String body){
        try {
            ScriptEngineManager sem = new ScriptEngineManager();
            engine = sem.getEngineByName("javascript");
            engine.eval(toCN());
            Invocable jsInvoke = (Invocable) engine;
            String msg = parse(body, jsInvoke)
                    .replaceAll("\\\\n", "\n")
                    .replaceAll("[\u0000]", "").replace("[DONE]","");

            return new OpenVo(true,msg);
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
            long millis = System.currentTimeMillis();
            log.info(millis+"解析:{}",body);
            return new OpenVo(false,"解析失败:"+millis);
        }
    }


    private static String parse(String body,Invocable jsInvoke) throws ScriptException, NoSuchMethodException {
        body = body.replace("data:[DONE]","");
        body = body.replaceAll("\\\\\"","\"");
        String[] bodyArray = body.split("data:data: ");
        StringBuilder result = new StringBuilder();
        for (String item : bodyArray) {
            if (!item.equals("")){
                item = item.trim();
                item = item.replace("{\"choices\":[{\"index\":0,\"text\":\"","");
                item = item.replace("\"}],\"created\":0,\"model\":\"trmodel\"}","");
                Object res = jsInvoke.invokeFunction("toCN", item);
                result.append(res);
            }
        }
        return point(result.toString());
    }

    private static String toCN(){
        return "function toCN(data){\n" +
                "    if (data.indexOf(\"\\\\u\") !== -1) {\n" +
                "        var valArr = data.split(\"\\\\u\"), result = \"\";\n" +
                "        var j = 0, length = valArr.length;\n" +
                "        for (; j < length; j++) {\n" +
                "            result += String.fromCharCode(parseInt(valArr[j], 16));\n" +
                "        }\n" +
                "        return result;\n" +
                "    }\n" +
                "    return data;\n" +
                "}";
    }

    public static String point(String result){
        String[] split = result.split("```");
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : split) {
            if (StrUtil.isBlank(stringBuilder.toString())){
                stringBuilder.append(s);
            }else {
                stringBuilder.append("\t\t\t\t\t\n\n\n ```").append(s);
            }
        }
        return stringBuilder.substring(0,stringBuilder.toString().length()-2);
    }

    public static String getStream(String data){
        try {
            String[] split = data.split("\n");
            JSONArray array = new JSONArray();
            for (String objJson : split) {
                if (StrUtil.isNotBlank(objJson.trim())){
                    array.put(JSONUtil.parseObj(objJson));
                }
            }
            JSONObject object;
            if (array.size() == 1 || array.size() == 2) {
                object = (JSONObject) array.get(0);
            }else {
                object = (JSONObject) array.get(array.size() - 2);
            }
            return object.getStr("data");
        }catch (Exception e){
            log.info("解析异常",e);
            e.printStackTrace();
            return "401";
        }
    }

}
